<?php
/**
 * Pagination Behavior.
 * @auth zmx@gootop.net
 */
class PaginationBehavior extends ModelBehavior {
	
	//分页返回
	var $return = array(
		'page'=>1,			 //当前页
		'total'=>0,			 //总页数
		'records'=>0,		 //总记录数
		'rows'=>array()		 //数据
	);
	
	//默认参数
	var $defaults = array(
		'_search'=>false,   //开启搜索
		'page'=>1,			//当前页
		'rows'=>20,			//页大小
		'sidx'=>'',		//排序字段
		'sord'=>'desc'		//排序方式
	);

//分页
function pagination(&$Model, $config = array(),$fields = array(),$conditions = array(),$recursive =  1) {
	$this->setupConfig($config);
	
	if(!$this->defaults['sidx'])  $this->defaults['sidx'] =$Model->name.'.id'; 
	
	if(empty($fields)) {
		$count = $Model->find('count', array('conditions' => $conditions));
	} else {
		$distinctInfo = "";
		foreach($fields as $key=>$value) {
			if(strpos($value,'DISTINCT') === false) {} 
			else {
				$distinctInfo = $value;   //提取DISTINCT条件
				break;
			}
		}
		$count = $Model->find('count', array('conditions' => $conditions, 'fields'=>$distinctInfo));
		
	}
	
	if( $count >0 ) { 
		$total_pages = ceil($count/$this->defaults['rows']); 
	} else { 
		$total_pages = 0; 
	} 
	
	if ($this->defaults['page'] > $total_pages) 
	$this->defaults['page']=$total_pages; 
	
	$params = array(
	    'conditions' => $conditions, //条件数组
	    'recursive' => $recursive, //整型
	    'fields' => $fields, //字段名数组
	    'order' => array($this->defaults['sidx'].' '.$this->defaults['sord']), //定义顺序的字符串或者数组
	    'limit' => $this->defaults['rows'], //整型
	    'page' => $this->defaults['page'], //整型
	    'callbacks' => false //other possible values are false, 'before', 'after'
	);
	$res =$Model->find('all',$params);
	
	$this->return['page']=$this->defaults['page'];
	$this->return['total']=$total_pages ;
	$this->return['records']=$count;
	
	$this->return['rows'] = $res;
	
	return $this->return; 
}

//配置参数
function setupConfig($config) {
	if (isset ( $config ['_search']) && !empty($config ['_search'])) {
		$this->defaults ['_search'] = $config ['_search'];
	}
	;
	if (isset ( $config ['page']) && !empty($config ['page'])) {
		$this->defaults ['page'] = $config ['page'];
	}
	;
	if (isset ( $config ['rows']) && !empty($config ['rows'])) {
		$this->defaults ['rows'] = $config ['rows'];
	}else{
		$this->defaults['rows'] =20;
	}
	;
	if (isset ( $config ['sidx'] )&& !empty($config ['sidx'])) {
		$this->defaults ['sidx'] = $config ['sidx'];
	}
	;
	if (isset ( $config ['sord']) && !empty($config ['sord'])) {
		$this->defaults ['sord'] = $config ['sord'];
	}
	;
}

//输出View
function showGridPagination(&$Model,$param =array()) {
	if(isset($param['action'])){
		$action = $param['action'];
	}else{
		$action = '/jsonPage';
	};
	if(isset($param['sortname'])){
		$sort = $param['sortname'];
	}else{
		$sort = 'id';
	};
	if(isset($param['sortorder'])){
		$sortOrder = $param['sortorder'];
	}else{
		$sortOrder = 'desc';
	};
	if(isset($param['page'])){
		$page = $param['page'];
	}else{
		$page = '20';
	};
	
	$script  = "<script>jQuery().ready(function(){jQuery(\"#grid_page\").jqGrid({"; 
	$script .="url:'".Router::url($action, true)."',";  
	$script .="datatype: \"json\",";
	$script .="colNames:".json_encode($param['colNames']).",";
	$script .="colModel:".json_encode($param['colModel']).",";
    $script .="viewrecords: true,";
    $script .="multiselect:true,";
    $script .="multiboxonly:true,";
	$script .="rowNum:$page,";
	$script .="rowList:[20,40,60],";
	$script .="pager: \"#pv_page\","; 
	$script .="sortname: '".$Model->name.".".$sort."',";
    $script .="sortorder: '".$sortOrder."',";
	$script .="mtype:'POST',";
	$script .="height:'100%',";
	$script .="autowidth: true,";
	$script .="width:'100%',";
	$script .="pginput:true,";
	$script .="pgbuttons : true,
		gridComplete: function(){
			Gootop.addDataGridOp('');
		  	Gootop.resizeGP = function(){
				jQuery(\"#grid_page\").jqGrid('setGridWidth',Gootop.param.contentWidth); 
				Gootop.resizeGPH();
			};
		},
		loadComplete: function(){
			Gootop.loadComplete();
			var PostData = jQuery(\"#grid_page\").jqGrid('getGridParam');
			PostData = PostData.postData;
			
			var keys = '".md5(Router::url($action, true))."';
			$.cookie(keys,O2String(PostData));
		},
		beforeRequest:function(){
			onceLoad();
			onceLoad = function(){};
		}
	}).jqGrid('navGrid','#pv_page',{
		edit:false,
		add:false,
		del:false,
		search:false,
		refresh:true
	});});
	onceLoad = function(){
		var keys = '".md5(Router::url($action, true))."';
		var cookiesVal = $.cookie(keys);
		postData = eval('(' + cookiesVal + ')');
		if(postData){
				var target =jQuery('#grid_page'); 
				target.jqGrid('setGridParam',{search:postData._search,postData:postData});
		}
	};
	</script>";
	return $script;
}

//输出View
function showTreePagination(&$Model,$param =array()) {
	if(isset($param['action'])){
		$action = $param['action'];
	}else{
		$action = '/jsonPage';
	};
	if(isset($param['ajax']) && $param['ajax']){
		$treeModel ="treeGridModel : 'adjacency',";
	}else{
		$treeModel ="";
	};
	$script  = "<script>jQuery().ready(function(){jQuery(\"#grid_page\").jqGrid({"; 
	$script .="url:'".Router::url($action, true)."',"; 
	$script .="datatype: \"json\",";
	$script .="colNames:".json_encode($param['colNames']).",";
	$script .="colModel:".json_encode($param['colModel']).",";
    $script .="viewrecords: false,";
	$script .="autowidth: true,";
	$script .="rowNum:4000,";
	$script .="pager: \"#pv_page\","; 
	$script .="ExpandColumn:'".$param['ExpandColumn']."',";
	$script .="sortname: '".$Model->name.".id', ";
    $script .="sortorder: \"desc\",";
    $script .="treeGrid:true,";
    $script .= $treeModel;
	$script .="mtype:'POST',";
	$script .="height:'100%',";
	$script .="pginput:false,";
	$script .="pgbuttons : false,
		gridComplete: function(){
		 	Gootop.addTreeGridOp('');
			Gootop.resizeGP = function(){
				jQuery(\"#grid_page\").jqGrid('setGridWidth',Gootop.param.contentWidth); 
				Gootop.resizeGPH();
			};
		}
	});
	});
	</script>";
	return $script;
}


}
